﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace T01WPF
{
    /// <summary>
    /// User的数据访问类：增删改查
    /// </summary>
    class UserDao
    {
        private static string connStr
            = "server=localhost;user=root;password=159874;database=test";
        /// <summary>
        /// 登陆检查
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public static int LoginCheck(string username,string password)
        {
            //默认无效用户名密码
            int number = 0;
            //构建mysql连接对象
            MySqlConnection conn = new MySqlConnection(connStr);

            try
            {
                //打开数据库链接
                conn.Open();
                //比较用户名和密码
                /* string sql = "SELECT COUNT(id) FROM `tb_users` WHERE `username`="
                     + username + ""+ "AND `password`='" + password + "'";*/
                
                string sql = "SELECT COUNT(id) FROM tb_users WHERE username='"+ username + "' AND password='"+password+"'";
                Debug.WriteLine("SQL语句:" + sql);
                //创建sql命令
                MySqlCommand cmd = new MySqlCommand(sql, conn);
                //执行说起来命
                object result = cmd.ExecuteScalar();
                if (result != null)
                {
                    number = Convert.ToInt32(result);
                }
            }
            catch(Exception ex){
                Debug.WriteLine("数据库访问异常");
                Debug.WriteLine("============");
                Debug.WriteLine(ex.ToString());
                Debug.WriteLine("============");

            }finally{
                if (conn != null) {
                    conn.Close();
}   
            }

            return number;
        }
        /// <summary>
        /// 获取所有用户列表
        /// </summary>
        /// <returns></returns>
        public static List<User> LoadData()
        {
            List<User> userList = new List<User>();
            MySqlConnection conn = new MySqlConnection(connStr);
            try
            {
                conn.Open();
                string sql = "SELECT * FROM tb_users";
                MySqlCommand cmd = new MySqlCommand(sql, conn);
                MySqlDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    User user = new User();
                    user.Id = Convert.ToInt64(rdr["id"]);
                    user.Username = Convert.ToString(rdr["username"]);
                    user.Password = Convert.ToString(rdr["password"]);
                    user.Nickname = Convert.ToString(rdr["nickname"]);
                    user.IsAdmin = Convert.ToInt64(rdr["is_admin"]) == 1 ? true : false;
                    userList.Add(user);

                }
                rdr.Close();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
            finally
            {
                if (conn != null)
                    conn.Close();
            }
            return userList;
        }

        /// <summary>
        /// 按条件获取所有用户列表
        /// </summary>
        /// <returns></returns>


        public static List<User> LoadData(string condition)
        {
            List<User> userList = new List<User>();
            MySqlConnection conn = new MySqlConnection(connStr);
            try
            {
                conn.Open();
                //模糊查询
                string sql = "SELECT * FROM tb_users WHERE username LIKE @username OR nickname LIKE @nickname";
                MySqlCommand cmd = new MySqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("@username", "%" + condition + "%");
                cmd.Parameters.AddWithValue("@nickname", "%" + condition + "%");
                //安全的参数
                MySqlDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    User user = new User();
                    user.Id = Convert.ToInt64(rdr["id"]);
                    user.Username = Convert.ToString(rdr["username"]);
                    user.Password = Convert.ToString(rdr["password"]);
                    user.Nickname = Convert.ToString(rdr["nickname"]);
                    user.IsAdmin = Convert.ToInt64(rdr["is_admin"]) == 1 ? true : false;
                    userList.Add(user);
                }
                rdr.Close();
            }
           
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                }

            }
            Debug.WriteLine(userList.Count);
            return userList;
        }

        /// <summary>
        /// 新增用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>

        public static long Insert(User user)
        {
            long insertId = 0;
            MySqlConnection conn = new MySqlConnection(connStr);
            try
            {
                conn.Open();
                string sql = "INSERT INTO tb_users "
                    + "(username, password, nickname, is_admin) "
                    + "VALUES "
                    + "(@username, @password, @nickname, @is_admin) ";
                MySqlCommand cmd = new MySqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("@username", user.Username);
                cmd.Parameters.AddWithValue("@password", user.Password);
                cmd.Parameters.AddWithValue("@nickname", user.Nickname);
                cmd.Parameters.AddWithValue("@is_admin", user.IsAdmin);
                cmd.ExecuteNonQuery();
                insertId = cmd.LastInsertedId;
            }
            catch (Exception e)
            {
                Debug.WriteLine("数据插入异常" + e.ToString());
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                }
            }
            return insertId;
        }


        /// <summary>
        /// 更新用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>

        public static void Update(User user)
        {
            MySqlConnection conn = new MySqlConnection(connStr);
            try
            {
                conn.Open();
                string sql = "Update tb_users SET "
                    + "username=@username, "
                    + "password=@password, "
                    + "nickname=@nickname, "
                    + "is_admin=@is_admin "
                    + "WHERE id=@id";
                MySqlCommand cmd = new MySqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("@username", user.Username);
                cmd.Parameters.AddWithValue("@password", user.Password);
                cmd.Parameters.AddWithValue("@nickname", user.Nickname);
                cmd.Parameters.AddWithValue("@is_admin", user.IsAdmin);
                cmd.Parameters.AddWithValue("@id", user.Id);
                cmd.ExecuteNonQuery();
                
            }
            catch (Exception e)
            {
                Debug.WriteLine("数据更新异常" + e.ToString());
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                }
            }
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>

        public static void Delete(long id)
        {
            MySqlConnection conn = new MySqlConnection(connStr);
            try
            {
                conn.Open();
                string sql = "DELETE FROM tb_users WHERE id=@id";
                MySqlCommand cmd = new MySqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("@id", id);
                cmd.ExecuteNonQuery();

            }
            catch (Exception e)
            {
                Debug.WriteLine("数据删除异常" + e.ToString());
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                }
            }
        }
    }
}
